<template>
  <div class="order-page">

    <!-- 顶部功能区 -->
    <div class="header">
      <div class="header-left">
        <img src="@/assets/coffee_logo.png" alt="Logo" class="logo">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="menuItems"
          @click="handleMenuClick"
        />
      </div>
      <div class="header-right">
        <div class="cart-section">
          <a-button type="default" @click="showStoreModal">
            <shop-outlined /> {{ currentStoreName ? `当前门店：${currentStoreName}` : '选择门店' }}
          </a-button>
          <a-badge :count="cartItemCount">
            <shopping-cart-outlined class="cart-icon" @click="showCartPanel" />
          </a-badge>
          <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
          <div class="user-login-status">
            <div v-if="loginUserStore.loginUser.userId">
              <a-dropdown>
                <div class="user-info">
                  <a-avatar :size="32" :src="loginUserStore.loginUser.avatar">
                    {{ loginUserStore.loginUser.userName?.charAt(0)?.toUpperCase() }}
                  </a-avatar>
                  <span class="username" :title="loginUserStore.loginUser.userName">{{ loginUserStore.loginUser.userName ?? '未命名'}}</span>
                </div>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="profile" @click="showProfileModal">
                      <user-outlined />
                      <span>个人信息</span>
                    </a-menu-item>
                    <a-menu-item key="logout" @click="handleLogout">
                      <logout-outlined />
                      <span>退出</span>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
            <div v-else>
              <a-button type="primary" @click="showLoginModal">登录</a-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧菜单区 -->
      <div class="menu-section">
        <template v-if="selectedStoreId">
          <a-tabs
            v-model:activeKey="activeCategory"
            @change="handleCategoryChange"
            :defaultActiveKey="categories.length > 0 ? categories[0].categoryId.toString() : ''"
            forceRender
          >
            <a-tab-pane
              v-for="category in categories"
              :key="category.categoryId"
              :tab="category.categoryName"
            >
              <div class="product-grid">
                <div v-for="product in category.productList" :key="product.productId" class="product-card" @click="selectProduct(product)">
                  <div class="product-image" :class="{ 'sold-out': !product.stock }">
                    <img :src="product.imageUrlList[0]" :alt="product.name">
                    <div v-if="!product.stock" class="sold-out-mask">售罄</div>
                  </div>
                  <div class="product-info">
                    <h3>{{ product.name }}</h3>
                    <p class="price">¥{{ product.basePrice }}</p>
                  </div>
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </template>
        <template v-else>
          <div class="empty-store">
            <shop-outlined style="font-size: 48px; color: #999; margin-bottom: 16px;" />
            <p>请先选择门店</p>
          </div>
        </template>
      </div>

      <!-- 右侧定制区 -->
      <div class="customize-section">
        <template v-if="selectedProduct">
          <div class="product-preview">
            <a-carousel ref="carousel" autoplay>
              <div v-for="(image, index) in selectedProduct.imageUrlList" :key="index" class="carousel-item">
                <img :src="image" :alt="selectedProduct.name">
              </div>
            </a-carousel>
            <div class="carousel-nav">
              <div class="carousel-prev" @click="prevImage"><left-outlined /></div>
              <div class="carousel-next" @click="nextImage"><right-outlined /></div>
            </div>
          </div>
          <div class="customize-options">
            <h2>{{ selectedProduct.name }}</h2>
            <div class="product-description">
              {{ selectedProduct.description }}
            </div>
            <div class="param-options">
              <div v-for="param in sortedParamList" :key="param.id" class="param-group">
                <h3>
                  {{ param.name }}
                  <span v-if="param.isRequired === 1" class="required-mark">*</span>
                </h3>
                <div class="param-values">
                  <!-- 单选类型 -->
                  <a-radio-group
                    v-if="param.type === 0"
                    v-model:value="selectedProduct.paramValues[param.id]"
                    class="param-radio-group"
                  >
                    <a-radio-button
                      v-for="value in getSortedValueList(param.valueList)"
                      :key="value.id"
                      :value="value.id"
                    >
                      <span class="param-value">{{ value.value }}</span>
                      <span v-if="value.priceOffset > 0" class="price-offset">
                        +¥{{ value.priceOffset.toFixed(2) }}
                      </span>
                    </a-radio-button>
                  </a-radio-group>

                  <!-- 多选类型 -->
                  <a-checkbox-group
                    v-else
                    v-model:value="selectedProduct.paramValues[param.id]"
                    class="param-checkbox-group"
                  >
                    <a-checkbox
                      v-for="value in getSortedValueList(param.valueList)"
                      :key="value.id"
                      :value="value.id"
                    >
                      <span class="param-name">{{ param.name }}：</span>
                      <span class="param-value">{{ value.value }}</span>
                      <span v-if="value.priceOffset > 0" class="price-offset">
                        +¥{{ value.priceOffset.toFixed(2) }}
                      </span>
                    </a-checkbox>
                  </a-checkbox-group>
                </div>
              </div>
            </div>
            <div class="remark-section">
              <a-textarea
                v-model:value="remark"
                placeholder="请输入备注信息（选填）"
                :rows="3"
                :maxlength="200"
                show-count
              />
            </div>
            <div class="quantity-selector">
              <a-button-group>
                <a-button @click="decreaseQuantity">-</a-button>
                <a-button>{{ selectedProduct.quantity }}</a-button>
                <a-button @click="increaseQuantity">+</a-button>
              </a-button-group>
            </div>
            <a-button type="primary" block @click="updateCart">
              {{ isUpdating ? '更新选项' : '加入购物车' }}
            </a-button>
          </div>
        </template>
        <div v-else class="empty-state">
          <coffee-outlined />
          <p>请选择商品进行定制</p>
        </div>
      </div>
    </div>

    <!-- 购物车面板 -->
    <a-drawer
      title="购物车"
      placement="right"
      :visible="cartVisible"
      @close="hideCartPanel"
      width="400"
    >
      <div class="cart-content">
        <div class="cart-items">
          <div v-for="item in cartItems" :key="item.id" class="cart-item">
            <img :src="item.imageUrlList[0]" :alt="item.name">
            <div class="item-info">
              <h4>{{ item.name }}</h4>
              <p>{{ item.options }}</p>
              <p v-if="item.remark" class="item-remark">备注：{{ item.remark }}</p>
              <div class="item-price">¥{{ item.basePrice }}</div>
            </div>
            <div class="item-actions">
              <a-button-group>
                <a-button @click="decreaseCartItem(item)">-</a-button>
                <a-button>{{ item.quantity }}</a-button>
                <a-button @click="increaseCartItem(item)">+</a-button>
              </a-button-group>
              <a-button type="link" danger @click="removeFromCart(item)">
                <delete-outlined />
              </a-button>
            </div>
          </div>
        </div>
        <div class="cart-summary">
          <div class="summary-item">
            <span>小计</span>
            <span>¥{{ subtotal.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span>优惠</span>
            <span>-¥{{ discount.toFixed(2) }}</span>
          </div>
          <div class="summary-item total">
            <span>实付</span>
            <span>¥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <a-button
            type="primary"
            block
            @click="checkout"
            :loading="isCheckingOut"
            :disabled="cartItems.length === 0"
          >
            去结算
          </a-button>
        </div>
      </div>
    </a-drawer>

    <!-- 个人信息弹窗 -->
    <a-modal
      v-model:visible="profileModalVisible"
      title="个人信息"
      @ok="hideProfileModal"
      @cancel="hideProfileModal"
      :footer="null"
    >
      <div class="profile-container">
        <div class="profile-avatar">
          <template v-if="!isEditing">
            <a-avatar :size="64" :src="loginUserStore.loginUser.avatar">
              {{ loginUserStore.loginUser.userName?.charAt(0)?.toUpperCase() }}
            </a-avatar>
          </template>
          <template v-else>
            <a-upload
              v-model:file-list="fileList"
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              @change="handleChange"
              :max-count="1"
              :customRequest="customRequest"
            >
              <div v-if="imageUrl" class="avatar-preview">
                <img :src="imageUrl" alt="avatar" />
              </div>
              <div v-else class="avatar-placeholder">
                <plus-outlined />
                <div style="margin-top: 8px">上传头像</div>
              </div>
            </a-upload>
          </template>
        </div>
        <div class="profile-info">
          <div class="profile-item">
            <span class="profile-label">用户名：</span>
            <template v-if="!isEditing">
              <span class="profile-value">{{ loginUserStore.loginUser.userName }}</span>
            </template>
            <template v-else>
              <a-input v-model:value="formState.userName" placeholder="请输入用户名" />
            </template>
          </div>
          <div class="profile-item">
            <span class="profile-label">用户ID：</span>
            <span class="profile-value">{{ loginUserStore.loginUser.userId }}</span>
          </div>
          <div class="profile-item">
            <span class="profile-label">手机号：</span>
            <span class="profile-value">{{ loginUserStore.loginUser.phone }}</span>
          </div>
        </div>
        <div class="profile-actions">
          <template v-if="!isEditing">
            <a-button type="primary" @click="handleEditProfile">
              <edit-outlined /> 编辑
            </a-button>
          </template>
          <template v-else>
            <a-button type="primary" @click="handleSaveProfile" style="margin-right: 8px;">
              <check-outlined /> 保存
            </a-button>
            <a-button @click="isEditing = false">
              <close-outlined /> 取消
            </a-button>
          </template>
        </div>
      </div>
    </a-modal>

    <!-- 登录弹窗 -->
    <LoginModal ref="loginModalRef" />

    <!-- 切换本店弹窗 -->
    <a-modal
      v-model:visible="storeModalVisible"
      title="选择门店"
      @ok="handleStoreSelect"
      @cancel="hideStoreModal"
      :footer="null"
      width="600px"
    >
      <div class="store-list">
        <template v-if="storeList.length > 0">
          <a-radio-group v-model:value="selectedStoreId" class="store-radio-group">
            <div v-for="store in storeList" :key="store.storeId" class="store-item">
              <a-radio :value="store.storeId" class="store-radio">
                <div class="store-content">
                  <div class="store-image">
                    <img :src="store.coverImage" :alt="store.storeName" />
                  </div>
                  <div class="store-info">
                    <div class="store-name">{{ store.storeName }}</div>
                    <div class="store-address">
                      <environment-outlined /> {{ store.address }}
                    </div>
                    <div class="store-details">
                      <clock-circle-outlined /> {{ store.openingHours }}
                      <phone-outlined class="icon-margin" /> {{ store.phone }}
                    </div>
                  </div>
                </div>
              </a-radio>
            </div>
          </a-radio-group>
        </template>
        <template v-else>
          <div class="empty-store-list">
            <shop-outlined style="font-size: 48px; color: #999;" />
            <p>暂无营业门店</p>
          </div>
        </template>
      </div>
      <div class="store-actions">
        <a-button type="primary" @click="handleStoreSelect" :disabled="!selectedStoreId">
          确认选择
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, h, watch, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import {
  HomeOutlined,
  ShoppingCartOutlined,
  PlusOutlined,
  DeleteOutlined,
  CoffeeOutlined,
  UserOutlined,
  EditOutlined,
  CheckOutlined,
  CloseOutlined,
  LogoutOutlined,
  ShopOutlined,
  FileTextOutlined,
  EnvironmentOutlined,
  ClockCircleOutlined,
  PhoneOutlined,
  LeftOutlined,
  RightOutlined
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useLoginStore } from "@/store/useLoginUserStore";
import { editUser } from "@/api/user";
import { uploadFile } from "@/api/file";
import LoginModal from '@/components/LoginModal.vue';
import { MenuProps } from 'ant-design-vue';
import type { UploadProps } from 'ant-design-vue';
import type { AxiosResponse } from 'axios';
import { listAllStores, listStoreProduct, storeProductDetail } from "@/api/store";
import { createOrder } from "@/api/order";

const router = useRouter();
const loginUserStore = useLoginStore();
const loginModalRef = ref();
// 控制个人信息弹窗的显示
const profileModalVisible = ref(false);
// 控制是否处于编辑状态
const isEditing = ref(false);
// 表单数据
const formState = reactive({
  userName: ''
});

// 状态管理
const activeCategory = ref('');
const cartVisible = ref(false);
const selectedProduct = ref<any>(null);
const isUpdating = ref(false);

// 门店相关状态
const storeModalVisible = ref(false);
const selectedStoreId = ref<string>();
const currentStoreName = ref<string>('');
const storeList = ref<Array<{
  storeId: string;
  storeName: string;
  address: string;
  phone: string;
  openingHours: string;
  status: number;
  coverImage: string;
}>>([]);

// 添加一个标记来记录用户是否点击了需要登录的菜单项
const pendingNavigation = ref<string | null>(null);

// 在 script setup 中添加状态
const isCheckingOut = ref(false);
const remark = ref('');

// 头像上传相关
const fileList = ref<any[]>([]);
const imageUrl = ref('');

// 检查用户是否登录
const checkLogin = () => {
  if (!loginUserStore.loginUser.userId) {
    showLoginModal();
    return false;
  }
  return true;
};

// 获取门店列表
const fetchStoreList = async () => {
  if (!checkLogin()) return;

  try {
    const res = await listAllStores();
    if (res.data.code === 200) {
      // 过滤掉公共门店（storeName为"公共门店"的门店）和未营业的门店（status不为0的门店）
      storeList.value = res.data.data.filter((store: any) => 
        store.storeName !== '公共门店' && store.status === 0
      );
    } else {
      message.error(res.data.msg || '获取门店列表失败');
    }
  } catch (error) {
    console.error('获取门店列表失败:', error);
    message.error('获取门店列表失败，请稍后重试');
  }
};

// 获取门店商品列表
const fetchStoreProducts = async (storeId: string) => {
  if (!checkLogin()) return;

  try {
    console.log('正在获取门店ID为', storeId, '的商品列表...');

    const res = await listStoreProduct(storeId);
    if (res.data.code === 200) {
      console.log('成功获取商品列表数据:', res.data.data);

      // 为每个商品添加UI交互所需的额外属性
      const processedData = res.data.data.map((category: {
        categoryId: number;
        categoryName: string;
        productList: Array<any>;
      }) => ({
        ...category,
        productList: category.productList.map((product: any) => ({
          ...product,
          stock: true,
          selectedSize: 'medium',
          temperature: 'hot',
          sweetness: 50,
          additions: [],
          quantity: 1
        }))
      }));

      console.log('处理后的分类数据:', processedData);

      // 设置数据
      categories.value = processedData;
      console.log('categories设置完成, 长度 =', categories.value.length);

    } else {
      console.error('获取商品列表失败, 错误信息:', res.data.msg);
      message.error(res.data.msg || '获取商品列表失败');
    }
  } catch (error) {
    console.error('获取商品列表异常:', error);
    message.error('获取商品列表失败，请稍后重试');
  }
};

// 模拟数据
const categories = ref<Array<{
  categoryId: number;
  categoryName: string;
  productList: Array<{
    productId: number;
    name: string;
    description: string;
    category_id: number;
    imageUrlList: string[];
    basePrice: number;
    sort: number;
    create_time: string;
    update_time: string;
    templateId: number;
    templateName: string;
    // 用于UI交互的额外属性
    stock: boolean;
    selectedSize: string;
    temperature: string;
    sweetness: number;
    additions: string[];
    quantity: number;
  }>;
}>>([]);

const cartItems = ref<any[]>([]);
const sweetnessMarks = {
  0: '无糖',
  25: '1/4糖',
  50: '半糖',
  75: '3/4糖',
  100: '全糖'
};

// 计算属性
const cartItemCount = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.quantity, 0);
});

const subtotal = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.basePrice * item.quantity, 0);
});

const discount = computed(() => {
  return 0; // 取消优惠
});

const totalAmount = computed(() => {
  return subtotal.value; // 直接返回小计金额
});

// 导航菜单相关
const current = ref<string[]>([]);
const menuItems = ref<MenuProps['items']>([
  {
    key: '/order',
    icon: () => h(HomeOutlined),
    label: '首页',
    title: '首页',
  },
  {
    key: '/my-orders',
    icon: () => h(FileTextOutlined),
    label: '我的订单',
    title: '我的订单',
  }
]);

// 根据当前路由设置选中的菜单项
const setCurrentMenu = () => {
  const path = router.currentRoute.value.path;
  current.value = [path];
};

// 监听路由变化
watch(() => router.currentRoute.value.path, () => {
  setCurrentMenu();
});

// 初始化时设置当前菜单
onMounted(() => {
  setCurrentMenu();
});

const showCartPanel = () => {
  if (!checkLogin()) return;
  cartVisible.value = true;
};

const hideCartPanel = () => {
  cartVisible.value = false;
};

const handleCategoryChange = (key: string) => {
  console.log('分类切换, key =', key);
  activeCategory.value = key;
  console.log('分类切换后, activeCategory =', activeCategory.value);
  console.log('分类切换后, 当前分类下商品数量 =', currentCategoryProducts.value.length);
};

const selectProduct = async (product: any) => {
  if (!checkLogin()) return;

  try {
    if (!selectedStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    console.log('正在获取商品详情，storeId:', selectedStoreId.value, 'productId:', product.productId);

    const res = await storeProductDetail(selectedStoreId.value, product.productId);
    console.log('商品详情响应:', res);

    if (res.data.code === 200) {
      const productData = res.data.data;
      console.log('获取到的商品数据:', productData);

      // 初始化参数值对象
      const paramValues: Record<number, number | number[]> = {};
      productData.paramList.forEach((param: any) => {
        if (param.type === 0) {
          // 单选类型，设置默认值为第一个选项
          if (param.valueList && param.valueList.length > 0) {
            paramValues[param.id] = param.valueList[0].id;
          }
        } else {
          // 多选类型，初始化为空数组
          paramValues[param.id] = [];
        }
      });

      selectedProduct.value = {
        ...productData,
        quantity: 1,
        paramValues
      };

      isUpdating.value = false;
      console.log('设置selectedProduct:', selectedProduct.value);
    } else {
      message.error(res.data.msg || '获取商品详情失败');
    }
  } catch (error) {
    console.error('获取商品详情失败:', error);
    message.error('获取商品详情失败，请稍后重试');
  }
};

const addToCart = (product: any) => {
  // 构建选项字符串
  const options = [...product.paramList]
    .sort((a, b) => a.sort - b.sort) // 按照sort值排序
    .map((param: any) => {
      const selectedValues = [];
      if (param.type === 0) {
        // 单选类型
        const selectedValue = param.valueList.find((v: any) => v.id === product.paramValues[param.id]);
        if (selectedValue) {
          selectedValues.push(selectedValue.value);
        }
      } else {
        // 多选类型
        const selectedIds = product.paramValues[param.id] || [];
        param.valueList.forEach((v: any) => {
          if (selectedIds.includes(v.id)) {
            selectedValues.push(v.value);
          }
        });
      }
      return selectedValues.join('、');
    })
    .filter((option: string) => option) // 过滤掉空字符串
    .join(' / ');

  // 构建参数值ID列表
  const paramValueIdList = Object.entries(product.paramValues).reduce((acc: number[], [paramId, value]) => {
    if (Array.isArray(value)) {
      // 多选类型，直接添加所有选中的值ID
      acc.push(...value);
    } else {
      // 单选类型，添加选中的值ID
      acc.push(value as number);
    }
    return acc;
  }, []);

  const cartItem = {
    ...product,
    options,
    paramValueIdList,
    storeId: selectedStoreId.value,
    remark: remark.value
  };
  cartItems.value.push(cartItem);
  message.success('已添加到购物车');
  // 清空备注
  remark.value = '';
};

const updateCart = () => {
  // 验证必选参数
  const requiredParams = selectedProduct.value.paramList.filter((param: any) => param.isRequired === 1);
  const invalidParams = requiredParams.filter((param: any) => {
    if (param.type === 0) {
      // 单选类型，检查是否有选中值
      return !selectedProduct.value.paramValues[param.id];
    } else {
      // 多选类型，检查是否至少选中一个
      return !selectedProduct.value.paramValues[param.id]?.length;
    }
  });

  if (invalidParams.length > 0) {
    message.error(`请选择${invalidParams.map((param: any) => param.name).join('、')}`);
    return;
  }

  if (isUpdating.value) {
    // 更新购物车中的商品
    const index = cartItems.value.findIndex(item => item.id === selectedProduct.value.id);
    if (index !== -1) {
      // 构建选项字符串
      const options = [...selectedProduct.value.paramList]
        .sort((a, b) => a.sort - b.sort) // 按照sort值排序
        .map((param: any) => {
          const selectedValues = [];
          if (param.type === 0) {
            // 单选类型
            const selectedValue = param.valueList.find((v: any) => v.id === selectedProduct.value.paramValues[param.id]);
            if (selectedValue) {
              selectedValues.push(selectedValue.value);
            }
          } else {
            // 多选类型
            const selectedIds = selectedProduct.value.paramValues[param.id] || [];
            param.valueList.forEach((v: any) => {
              if (selectedIds.includes(v.id)) {
                selectedValues.push(v.value);
              }
            });
          }
          return selectedValues.join('、');
        })
        .filter((option: string) => option) // 过滤掉空字符串
        .join(' / ');

      // 构建参数值ID列表
      const paramValueIdList = Object.entries(selectedProduct.value.paramValues).reduce((acc: number[], [paramId, value]) => {
        if (Array.isArray(value)) {
          // 多选类型，直接添加所有选中的值ID
          acc.push(...value);
        } else {
          // 单选类型，添加选中的值ID
          acc.push(value as number);
        }
        return acc;
      }, []);

      cartItems.value[index] = {
        ...selectedProduct.value,
        options,
        paramValueIdList,
        storeId: selectedStoreId.value,
        remark: remark.value
      };
    }
  } else {
    // 添加新商品到购物车
    addToCart(selectedProduct.value);
  }
  hideCartPanel();
  // 清空备注
  remark.value = '';
};

const increaseQuantity = () => {
  if (selectedProduct.value) {
    selectedProduct.value.quantity++;
  }
};

const decreaseQuantity = () => {
  if (selectedProduct.value && selectedProduct.value.quantity > 1) {
    selectedProduct.value.quantity--;
  }
};

const increaseCartItem = (item: any) => {
  item.quantity++;
};

const decreaseCartItem = (item: any) => {
  if (item.quantity > 1) {
    item.quantity--;
  }
};

const removeFromCart = (item: any) => {
  const index = cartItems.value.indexOf(item);
  if (index !== -1) {
    cartItems.value.splice(index, 1);
  }
};

const checkout = async () => {
  if (!checkLogin()) return;

  if (cartItems.value.length === 0) {
    message.warning('购物车为空，请先添加商品');
    return;
  }

  if (!selectedStoreId.value) {
    message.warning('请先选择门店');
    return;
  }

  try {
    isCheckingOut.value = true;

    // 构建订单数据
    const orderData = {
      storeId: selectedStoreId.value,
      remark: cartItems.value.map(item => item.remark).filter(Boolean).join('、'),
      itemList: cartItems.value.map(item => ({
        paramValueIdList: item.paramValueIdList,
        productId: item.productId,
        quantity: item.quantity
      }))
    };

    // 调用创建订单接口
    const res = await createOrder(orderData);

    if (res.data.code === 200) {
      const orderId = res.data.data;
      message.success('订单创建成功');

      // 清空购物车
      cartItems.value = [];
      hideCartPanel();

      // 跳转到订单详情页
      router.push(`/my-orders`);
    } else {
      message.error(res.data.msg || '创建订单失败');
    }
  } catch (error) {
    console.error('创建订单失败:', error);
    message.error('创建订单失败，请稍后重试');
  } finally {
    isCheckingOut.value = false;
  }
};

// 显示个人信息弹窗
const showProfileModal = () => {
  if (!checkLogin()) return;
  profileModalVisible.value = true;
  // 重置编辑状态
  isEditing.value = false;
  // 初始化表单数据
  formState.userName = loginUserStore.loginUser.userName || '';
  imageUrl.value = loginUserStore.loginUser.avatar || '';
};

// 关闭个人信息弹窗
const hideProfileModal = () => {
  profileModalVisible.value = false;
  // 重置编辑状态
  isEditing.value = false;
};

// 显示登录弹窗
const showLoginModal = () => {
  loginModalRef.value.show();
};

// 处理编辑个人信息
const handleEditProfile = () => {
  if (!checkLogin()) return;
  isEditing.value = true;
};

// 处理保存个人信息
const handleSaveProfile = async () => {
  if (!checkLogin()) return;
  try {
    const res = await editUser({
      userName: formState.userName,
      avatar: imageUrl.value || loginUserStore.loginUser.avatar
    });

    if (res.data.code === 200) {
      loginUserStore.loginUser.userName = formState.userName;
      if (imageUrl.value) {
        loginUserStore.loginUser.avatar = imageUrl.value;
      }
      message.success('保存成功');
      isEditing.value = false;
      imageUrl.value = '';
      fileList.value = [];
    } else {
      message.error(res.data.msg || '保存失败');
    }
  } catch (error) {
    console.error('保存个人信息失败:', error);
    message.error('保存失败，请稍后重试');
  }
};

// 处理退出登录
const handleLogout = () => {
  // 清除本地存储的token
  localStorage.removeItem('token');
  // 清除用户信息
  loginUserStore.loginUser = {};
  // 清除待处理的导航
  pendingNavigation.value = null;
  // 跳转到首页
  router.push('/order');
};

// 显示门店选择弹窗
const showStoreModal = () => {
  if (!checkLogin()) return;
  storeModalVisible.value = true;
  fetchStoreList();
};

// 隐藏门店选择弹窗
const hideStoreModal = () => {
  storeModalVisible.value = false;
};

// 处理门店选择
const handleStoreSelect = () => {
  if (!checkLogin()) return;

  if (selectedStoreId.value) {
    const selectedStore = storeList.value.find(s => s.storeId === selectedStoreId.value);
    if (selectedStore) {
      currentStoreName.value = selectedStore.storeName;

      console.log('开始获取门店商品列表...');

      // 获取选中门店的商品列表
      fetchStoreProducts(selectedStoreId.value).then(() => {
        // 确保在数据加载完成后设置默认分类
        console.log('商品列表获取完成，categories.length =', categories.value.length);

        if (categories.value.length > 0) {
          console.log('设置默认分类:', categories.value[0].categoryId.toString());
          // 先将activeCategory设置为空，然后在nextTick中设置为第一个分类
          // 这样可以确保视图正确刷新
          activeCategory.value = '';

          nextTick(() => {
            activeCategory.value = categories.value[0].categoryId.toString();
            // 触发分类变化事件，确保商品列表更新
            console.log('触发分类变化事件, activeCategory =', activeCategory.value);
            handleCategoryChange(activeCategory.value);

            // 强制更新DOM
            nextTick(() => {
              console.log('DOM更新完成，当前选中的分类是:', activeCategory.value);
              console.log('当前分类下有商品数量:', currentCategoryProducts.value.length);
            });
          });
        } else {
          console.warn('获取到的分类列表为空');
        }
      }).catch(error => {
        console.error('获取商品列表时出错:', error);
      });

      message.success('已切换到新门店');
      hideStoreModal();
    }
  } else {
    console.warn('未选择任何门店');
  }
};

// 处理菜单点击
const handleMenuClick = ({ key }: { key: string }) => {
  if (key === '/my-orders' && !checkLogin()) {
    pendingNavigation.value = key;
    return;
  }
  router.push(key);
};

// 监听登录状态变化
watch(() => loginUserStore.loginUser.userId, (newValue) => {
  if (newValue && pendingNavigation.value) {
    // 登录成功后，清除待处理的导航
    pendingNavigation.value = null;
  }
});

// 当前选中分类的商品列表
const currentCategoryProducts = computed(() => {
  console.log('计算当前分类的商品列表, activeCategory =', activeCategory.value);
  console.log('计算当前分类的商品列表, categories.length =', categories.value.length);

  if (!activeCategory.value || categories.value.length === 0) {
    console.log('没有活动的分类或分类列表为空，返回空数组');
    return [];
  }

  const currentCategory = categories.value.find(
    category => category.categoryId.toString() === activeCategory.value
  );

  if (currentCategory) {
    console.log('找到对应分类:', currentCategory.categoryName);
    console.log('该分类下的商品数量:', currentCategory.productList.length);
  } else {
    console.warn('未找到对应的分类，categoryId =', activeCategory.value);
  }

  return currentCategory?.productList || [];
});

// 轮播图相关方法
const carousel = ref<{
  prev: () => void;
  next: () => void;
} | null>(null);

// 轮播图切换到上一张
const prevImage = () => {
  try {
    if (carousel.value) {
      carousel.value.prev();
    }
  } catch (error) {
    console.error('无法切换到上一张图片', error);
  }
};

// 轮播图切换到下一张
const nextImage = () => {
  try {
    if (carousel.value) {
      carousel.value.next();
    }
  } catch (error) {
    console.error('无法切换到下一张图片', error);
  }
};

// 添加计算属性来处理排序
const sortedParamList = computed(() => {
  if (!selectedProduct.value?.paramList) return []
  return [...selectedProduct.value.paramList].sort((a, b) => a.sort - b.sort)
})

const getSortedValueList = (valueList: any[]) => {
  return [...valueList].sort((a, b) => a.sort - b.sort)
}

// 头像上传相关
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片！');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！');
  }
  return isJpgOrPng && isLt2M;
};

const customRequest = async ({ file, onSuccess, onError }: any) => {
  try {
    const res = await uploadFile(file);
    if (res.data.code === 200) {
      onSuccess(res.data.data);
      imageUrl.value = res.data.data.url;
      message.success('头像上传成功');
    } else {
      onError(new Error(res.data.msg || '头像上传失败'));
    }
  } catch (error) {
    console.error('头像上传失败:', error);
    onError(error);
    message.error('头像上传失败，请稍后重试');
  }
};

const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
  fileList.value = newFileList;
};
</script>

<style scoped>
.order-page {
  min-height: 100vh;
  background: #F5F5F5;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 64px;
  background: white;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.logo {
  height: 40px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

.cart-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.cart-icon {
  font-size: 24px;
  color: #333;
  cursor: pointer;
  transition: color 0.3s;
}

.cart-icon:hover {
  color: #1890ff;
}

.total-amount {
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
}

.main-content {
  display: flex;
  margin-top: 64px;
  min-height: calc(100vh - 64px);
  background: #F5F5F5;
}

.menu-section {
  width: 70%;
  padding: 24px;
  background: white;
  border-radius: 8px;
  margin: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.customize-section {
  width: 30%;
  padding: 24px;
  background: white;
  border-radius: 8px;
  margin: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  margin-top: 24px;
}

.product-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  border: 1px solid #f0f0f0;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  border-color: #1890ff;
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-image:hover img {
  transform: scale(1.1);
}

.sold-out-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  font-weight: bold;
}

.product-info {
  padding: 16px;
}

.product-info h3 {
  margin: 0 0 8px;
  font-size: 16px;
  color: #333;
}

.price {
  color: #1890ff;
  font-size: 18px;
  font-weight: bold;
  margin: 8px 0;
}

.quick-options {
  margin: 8px 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.empty-state .anticon {
  font-size: 48px;
  margin-bottom: 16px;
}

.cart-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
}

.cart-item {
  display: flex;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.cart-item:hover {
  background-color: #fafafa;
}

.cart-item img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 16px;
}

.item-info {
  flex: 1;
}

.item-info h4 {
  margin: 0 0 8px;
  color: #333;
}

.item-price {
  color: #1890ff;
  font-weight: bold;
  margin-top: 8px;
}

.item-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.cart-summary {
  padding: 24px;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
  border-radius: 0 0 8px 8px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #666;
}

.summary-item.total {
  font-size: 18px;
  font-weight: bold;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  color: #1890ff;
}

:deep(.ant-tabs-nav) {
  margin-bottom: 24px;
}

:deep(.ant-tabs-tab) {
  padding: 12px 16px;
  transition: all 0.3s;
}

:deep(.ant-tabs-tab:hover) {
  color: #1890ff;
}

:deep(.ant-tabs-tab-active) {
  color: #1890ff;
}

:deep(.ant-radio-group) {
  display: flex;
  gap: 8px;
}

:deep(.ant-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.ant-slider) {
  margin: 16px 0;
}

:deep(.ant-slider-track) {
  background-color: #1890ff;
}

:deep(.ant-slider-handle) {
  border-color: #1890ff;
}

:deep(.ant-btn-primary) {
  background-color: #1890ff;
  border-color: #1890ff;
}

:deep(.ant-btn-primary:hover) {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

:deep(.ant-tag) {
  border-radius: 4px;
}

:deep(.ant-drawer-content) {
  border-radius: 8px 0 0 8px;
}

:deep(.ant-drawer-header) {
  border-radius: 8px 0 0 0;
}

.user-login-status {
  margin-left: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.username {
  font-size: 14px;
  color: #333;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.profile-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.profile-avatar {
  margin-bottom: 20px;
}

.profile-info {
  width: 100%;
}

.profile-item {
  margin-bottom: 12px;
  display: flex;
}

.profile-label {
  font-weight: bold;
  width: 80px;
  color: #666;
}

.profile-value {
  color: #333;
}

.profile-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.store-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 0 16px;
}

.store-radio-group {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.store-item {
  margin-bottom: 16px;
  width: 100%;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s;
}

.store-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.store-radio {
  width: 100%;
  padding: 16px;
  margin: 0;
}

.store-content {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  width: 100%;
}

.store-image {
  width: 80px;
  height: 80px;
  flex-shrink: 0;
  border-radius: 4px;
  overflow: hidden;
}

.store-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.store-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.store-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.store-address {
  color: #666;
  display: flex;
  align-items: center;
  gap: 8px;
}

.store-details {
  color: #999;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.store-radio :deep(.ant-radio) {
  align-self: flex-start;
  margin-top: 32px;
}

.store-radio :deep(.ant-radio + span) {
  padding-right: 0;
  padding-left: 8px;
}

.store-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

.header-left :deep(.ant-menu) {
  background: transparent;
  border-bottom: none;
}

.header-left :deep(.ant-menu-item) {
  color: #666;
}

.header-left :deep(.ant-menu-item-selected) {
  color: #1890ff;
}

.header-left :deep(.ant-menu-item:hover) {
  color: #1890ff;
}

.header-left :deep(.ant-menu-item::after) {
  display: none;
}

.header-left :deep(.ant-menu-item-selected::after) {
  display: block;
  border-bottom: 2px solid #1890ff;
}

.empty-store {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  padding: 48px;
}

.empty-store p {
  font-size: 16px;
  margin-top: 8px;
}

.product-preview {
  width: 100%;
  height: 220px;
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  position: relative;
}

.carousel-nav {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.carousel-prev,
.carousel-next {
  width: 32px;
  height: 32px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: all 0.3s;
  pointer-events: auto;
}

.carousel-prev:hover,
.carousel-next:hover {
  background: rgba(0, 0, 0, 0.5);
}

.product-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.carousel-item {
  height: 220px;
  line-height: 220px;
  text-align: center;
  background: #f8f8f8;
}

:deep(.ant-carousel .slick-slide) {
  height: 220px;
  overflow: hidden;
}

:deep(.ant-carousel .slick-dots) {
  bottom: 8px;
}

:deep(.ant-carousel .slick-dots li button) {
  background: #fff;
  opacity: 0.7;
}

:deep(.ant-carousel .slick-dots li.slick-active button) {
  background: #1890ff;
  opacity: 1;
}

.customize-options {
  padding: 16px 0;
}

.customize-options h2 {
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.product-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 16px;
  line-height: 1.5;
}

.template-description {
  color: #999;
  font-size: 13px;
  margin-bottom: 24px;
  line-height: 1.5;
}

.param-options {
  margin-bottom: 24px;
}

.param-group {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
}

.param-group h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 16px;
  font-weight: 500;
}

.param-values {
  margin-bottom: 0;
}

.param-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

:deep(.ant-radio-button-wrapper) {
  height: 36px;
  line-height: 34px;
  padding: 0 20px;
  border-radius: 4px;
  margin-right: 0;
  transition: all 0.3s;
  border: 1px solid #d9d9d9;
  background: white;
  display: flex;
  align-items: center;
  gap: 4px;
}

.param-name {
  color: #666;
  font-size: 13px;
}

.param-value {
  font-weight: 500;
}

:deep(.ant-radio-button-wrapper-checked) {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
}

:deep(.ant-radio-button-wrapper-checked .param-name) {
  color: rgba(255, 255, 255, 0.8);
}

:deep(.ant-radio-button-wrapper-checked .param-value) {
  color: white;
}

:deep(.ant-radio-button-wrapper-checked .price-offset) {
  color: #ffccc7;
}

:deep(.ant-radio-button-wrapper:hover) {
  color: #1890ff;
  border-color: #1890ff;
}

:deep(.ant-radio-button-wrapper:hover .param-name) {
  color: #1890ff;
}

:deep(.ant-radio-button-wrapper:hover .param-value) {
  color: #1890ff;
}

.price-offset {
  color: #ff4d4f;
  font-size: 12px;
  margin-left: 4px;
}

:deep(.ant-select) {
  width: 100%;
}

:deep(.ant-select-selector) {
  border-radius: 4px;
}

:deep(.ant-select-selection-item) {
  display: flex;
  align-items: center;
}

.required-mark {
  color: #ff4d4f;
  margin-left: 4px;
}

.param-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

:deep(.ant-checkbox-wrapper) {
  margin-right: 0;
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 4px;
}

:deep(.ant-checkbox-wrapper:hover) {
  border-color: #1890ff;
}

:deep(.ant-checkbox-wrapper-checked) {
  background: #e6f7ff;
  border-color: #1890ff;
}

:deep(.ant-checkbox-wrapper .ant-checkbox) {
  margin-right: 8px;
}

:deep(.ant-checkbox-wrapper .ant-checkbox-checked .ant-checkbox-inner) {
  background-color: #1890ff;
  border-color: #1890ff;
}

.remark-section {
  margin: 16px 0;
}

.remark-section :deep(.ant-input) {
  border-radius: 4px;
  resize: none;
}

.remark-section :deep(.ant-input:hover) {
  border-color: #40a9ff;
}

.remark-section :deep(.ant-input:focus) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.item-remark {
  color: #666;
  font-size: 13px;
  margin: 4px 0;
  font-style: italic;
}

.avatar-uploader {
  width: 128px;
  height: 128px;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.empty-store-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  color: #999;
}

.empty-store-list p {
  margin-top: 16px;
  font-size: 16px;
}
</style>
